'use strict';
const mongoose = require('mongoose');
const config = require('../config/config.unittest.js')({});

let ParserBetter = require('../app/utils/rss/parser');
let parserBetter = new ParserBetter({timeout: 10000});

const UserModel = require('../app/model/User')({
  mongoose,
});
const TopicModel = require('../app/model/Topic')({
  mongoose,
});

mongoose.connect(config.mongoose.url, config.mongoose.options, function (err) {
  if (err) {
    console.error('connect to %s error: ', config.mongoose, err.message);
    process.exit(1);
  }
});

async function main() {
  const users = await UserModel.find({sources: ['播客RSS'], rss: {$exists: false}});
  let cnt = users.length;
  for (let i = 0; i < cnt; i++) {
    const user = users[i];
    let default_boards;
    let default_tags;
    try {
      let feed = await parserBetter.parseURL(user.url);
      const itunes = feed.itunes;
      default_boards = getBoards(itunes.categories);
      default_tags = getTags(itunes.categoriesWithSubs);
      user.default_boards = default_boards;
      user.default_tags = default_tags;

      await user.save();
    } catch (e) {
      console.error(user.loginname, user.rss, '处理异常');
    } finally {
      console.log(i, cnt, user.loginname, default_boards, default_tags);
    }
  }


  process.exit(0);
}

main();


function getBoards(categories) {
  let boards = [...new Set(categories)].filter(v => v);
  boards = boards.map(v => v.replace('&amp;', '&'));
  return boards;
}

function getTags(categoriesWithSubs) {
  let tags = ['播客'];
  categoriesWithSubs.forEach(v => {
    tags.push(v.name);
    if (v.subs) {
      for (const sub of v.subs) {
        tags.push(sub.name);
      }
    }
  });
  tags = [...new Set(tags)].filter(v => v);
  tags = tags.map(v => v.replace('&amp;', '&'));
  return tags;
}


